package com.haizhi.crm.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.haizhi.crm.biz.builder.MsgSearchQoBuilder;
import com.haizhi.crm.biz.dao.*;
import com.haizhi.crm.biz.model.*;
import com.haizhi.crm.biz.service.*;
import com.haizhi.crm.common.constant.*;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.json.JSONUtils;
import com.haizhi.crm.common.log.GLog;
import com.haizhi.crm.common.model.PageResponse;
import com.haizhi.crm.common.model.Response;
import com.haizhi.crm.common.rest.RestService;
import com.haizhi.crm.common.util.ApplicationUtils;
import com.haizhi.crm.common.util.CommonUtils;
import com.haizhi.crm.common.util.Getter;
import com.haizhi.crm.search.builder.SearchQoBuilder;
import com.haizhi.crm.search.model.SearchQo;
import com.haizhi.crm.search.model.SearchResp;
import com.haizhi.crm.search.model.SearchVo;
import com.haizhi.crm.search.service.SearchService;
import com.haizhi.crm.sys.auth.dao.DepartmentDao;
import com.haizhi.crm.sys.auth.dao.RelationItemDao;
import com.haizhi.crm.sys.auth.dao.UserDao;
import com.haizhi.crm.sys.auth.model.RelationItemDo;
import com.haizhi.crm.sys.auth.model.UserResultVo;
import com.haizhi.crm.sys.auth.model.UserVo;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by yangyijun on 2018/6/3.
 */
@Service
public class EventServiceImpl implements EventService {

    private static final GLog LOG = new GLog(EventService.class);

    @Autowired
    private RestService searchHttpSender;

    @Autowired
    private SearchService searchService;
    @Autowired
    private VisitRecordDao visitRecordDao;
    @Autowired
    private HistoryViewDao historyViewDao;
    @Autowired
    private FavouriteDao favouriteDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private BrowseCountService browseCountService;
    @Autowired
    private VisitRecordService visitRecordService;
    @Autowired
    private RelationItemDao relationItemRepo;
    @Autowired
    private ConcernedDao concernedDao;
    @Autowired
    private UserShareDao userShareDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private HistoryViewService historyViewService;

    public Object getHotEvent(Schema schema) throws Exception {
        SearchQo request = new SearchQo();

        Map<String, Object> filterItem = new HashMap<>();
        filterItem.put("type", "range" );
        filterItem.put("field", "event_time" );

        Map range = new HashMap();
        Calendar now = Calendar.getInstance();
        range.put("to", now.getTime());
        now.set(Calendar.DATE, now.get(Calendar.DATE) - 7);
        range.put("from", now.getTime());

        filterItem.put("ranges", range);

        List<Map<String, Object>> filterList = new ArrayList<>();
        filterList.add(filterItem);

        request.setFilter(filterList);
        request.addSchema(schema.name());

        return getSearchResult(request);
    }

    public Response searchByCompany(String keyword, Schema schema, int pageNo, int pageSize) {
        SearchQo SearchQo = new SearchQo();
        SearchQo.addSchema(schema.name());
        SearchQo.setFilter(formFilter(keyword));
        SearchQo.setSort(formSoft("event_time", "desc" ));
        SearchQo.setPageNo(pageNo);
        SearchQo.setPageSize(pageSize);
        Object resp = this.searchService.search(SearchQo);
        return Response.success(resp);
    }

    private List<Map<String, Object>> formFilter(String companyKey) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "match" );
        map.put("field", "name" );
        map.put("values", new String[]{companyKey});

        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);

        return list;
    }

    private List<Map<String, Object>> formSoft(String field, String order) {
        Map<String, Object> map = new HashMap<>();
        map.put("field", field);
        map.put("order", order);

        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);

        return list;
    }

    public List getEventOutterRecentBrowse() {
        Long userID = CommonUtils.getUserID();
        List list = this.historyViewDao.findByEntityTypeAndUserId(userID, "event_outter", 5);
        return list;
    }

    public List getEventInnerRecentBrowse() {
        Long userID = CommonUtils.getUserID();
        List list = this.historyViewDao.findByEntityTypeAndUserId(userID, "event_inner", 5);
        return list;
    }

    /**
     * 查询事件基本信息
     *
     * @param schema
     * @param enventKey
     * @return
     */
    public Object getBasicInfo(Schema schema, String enventKey) throws Exception {
        browseCountService.count(schema.getValue(), enventKey);
        SearchQo searchQo = MsgSearchQoBuilder.get(CrmSchema.CRM, schema.getValue(), enventKey);
        SearchVo searchVo = searchService.search(searchQo);
        List<Map<String, Object>> datas = JSONUtils.toListMap(searchVo.getSearchResp().getData());
        if (datas.size() == 0) {
            return null;
        }
        Map<String, Object> data = datas.get(0);
        buildCompanyInfo(schema.getValue(), data);
        historyViewService.save(schema.getValue(), enventKey, Getter.get("title", data));
        return data;
    }

    private void getCompanyVo(Map<String, Object> data, String companyKeys) {
        CompanyVo companyVo = companyService.queryByCustomerKey(companyKeys);
        Map<String, Object> companyNameAndKey = new HashMap<>();
        companyNameAndKey.put("object_key", companyVo.getObjectKey());
        companyNameAndKey.put("name", companyVo.getName());
        data.put("company", companyNameAndKey);
    }

    public Response findAssociatedCompanys(String companyKeys) {
        try {
            SearchQoBuilder searchQoBuilder = new SearchQoBuilder();
            searchQoBuilder.setGraph(CrmSchema.CRM);
            searchQoBuilder.addSchemas(CrmSchema.COMPANY);
            searchQoBuilder.addTermFilter("object_key", companyKeys.split("," ));
            Object data = searchService.search(searchQoBuilder.get()).getSearchResp().getData();
            List<Map<String, Object>> companys = JSONUtils.jsonToListMap(JSON.toJSONString(data));
            List<Map<String, Object>> companyVos = new ArrayList<>();
            for (Map<String, Object> company : companys) {
                Map<String, Object> companyVo = new HashMap<>();
                companyVo.put("name", company.get("name" ));
                List<RelationItemDo> relationItemDos = relationItemRepo.findByEntityKeyAndRelationId(company.get("object_key" ).toString(), 1l);
                List<UserVo> userVos = relationItemDos.stream().map(n -> userDao.findBy(n.getUserId())).filter(n -> n != null).collect(Collectors.toList());
                companyVo.put("customerManager", userVos);
                companyVo.put("objectKey", company.get("object_key" ));
                companyVos.add(companyVo);
            }
            return Response.success(companyVos);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.EVENT_QUERY_ERROR, e);
        }
    }

    public List<VisitRecordResultVo> getVisitRecord(Schema type, String id, Integer pageNo, Integer pageSize) {

        Integer offset = pageNo * pageSize - pageSize;
        if (pageNo == 0) {
            offset = 0;
        }

        List<VisitRecordDo> visitRecords = null;
        List<VisitRecordResultVo> result = new ArrayList<>();
        if (type == Schema.Inner_Event) {
            visitRecords = this.visitRecordDao.queryUserRelationByInnerEvent(id, offset, pageSize);
        } else if (type == Schema.Outer_Event) {
            visitRecords = this.visitRecordDao.queryUserRelationByOutterEvent(id, offset, pageSize);
        }


        if (visitRecords != null && visitRecords.size() > 0) {
            for (VisitRecordDo vr : visitRecords) {
                VisitRecordResultVo vrr = new VisitRecordResultVo();
                try {
                    PropertyUtils.copyProperties(vrr, vr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                this.visitRecordService.setDetailInfo(vrr);
                result.add(vrr);
            }
        }
        return result;
    }

    public Integer getVisitRecordCount(Schema type, String id) {
        if (type == Schema.Inner_Event) {
            return this.visitRecordDao.queryUserRelationByInnerEventCount(id);
        }

        return this.visitRecordDao.queryUserRelationByOutterEventCount(id);
    }

    public Response findEventsByName(String name, String eventSchema) {
        try {
            SearchQoBuilder searchQoBuilder = new SearchQoBuilder();
            searchQoBuilder.setGraph(CrmSchema.CRM);
            searchQoBuilder.addSchemas(eventSchema);
            searchQoBuilder.setKeyword(name);
            searchQoBuilder.addMatchQuery("title" );

            List<EventVo> eventList = new ArrayList<>();
            SearchVo searchVo = this.searchService.search(searchQoBuilder.get());
            Object data = searchVo.getSearchResp().getData();
            List<Map<String, Object>> events = JSONUtils.jsonToListMap(JSON.toJSONString(data));
            for (Map<String, Object> eventMap : events) {
                eventList.add(this.eventBeanConvert(eventMap));
            }
            return Response.success(eventList);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.EVENT_QUERY_ERROR, e);
        }
    }

    /**
     * 封装事件数据
     *
     * @param eventMap
     * @return
     */
    private EventVo eventBeanConvert(Map<String, Object> eventMap) {
        EventVo event = new EventVo();
        event.setName(Getter.get("title", eventMap));
        event.setObjectKey(Getter.get("object_key", eventMap));
        event.setType(Getter.get("type_", eventMap));
        event.setEventDate(Getter.get("event_time", eventMap));
        return event;
    }

    private String getSearchResult(SearchQo request) throws Exception {
        LOG.info(JSON.toJSON(request));
        return this.searchHttpSender.doPost(ApplicationUtils.getSearchUri(), request, String.class);
    }


    public Response findInnerEvents(CustomerEventQo customerEventQo) {
        try {
            return getCustomerEventResponse(customerEventQo, CrmSchema.EVENT_INNER, "customer_key" );
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.INNER_EVENT_QUERY_ERROR, e);
        }
    }

    public Response findOuterEvents(CustomerEventQo customerEventQo) {
        try {
            return getCustomerEventResponse(customerEventQo, CrmSchema.EVENT_OUTTER, "company_keys" );
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.EVENT_QUERY_ERROR, e);
        }
    }

    private Response getCustomerEventResponse(CustomerEventQo customerEventQo, String schema, String customerField) {
        Integer pageNo = customerEventQo.getPageNo();
        Integer pageSize = customerEventQo.getPageSize();
        String customerKey = customerEventQo.getCustomerKey();
        String eventType = customerEventQo.getEventType();

        SearchQoBuilder searchQoBuilder = new SearchQoBuilder();
        searchQoBuilder.setGraph(CrmSchema.CRM);
        searchQoBuilder.addSchemas(schema);
        searchQoBuilder.setPageNo(pageNo);
        searchQoBuilder.setPageSize(pageSize);

        if (!"all".equals(eventType)) {
            searchQoBuilder.addTermFilter("type_", eventType);
        }
        if (CrmSchema.EVENT_OUTTER.equals(schema)) {
            searchQoBuilder.setKeyword(customerKey);
            searchQoBuilder.addMatchQuery(customerField);
        } else {
            searchQoBuilder.addTermFilter(customerField, customerKey);
        }
        searchQoBuilder.addSort("event_time", "desc" );
        SearchResp resp = this.searchService.search(searchQoBuilder.get()).getSearchResp();
        List<Map<String, Object>> datas = JSONUtils.toListMap(resp.getData());
        for (Map<String, Object> data : datas) {
            int favouriteCount = favouriteDao.findFavouriteCount(CommonUtils.getUserID(), schema, Getter.get("object_key", data));
            data.put("favourited", favouriteCount >= 1 ? true : false);

            buildCompanyInfo(schema, data);
        }

        Long total = resp.getTotal();
        return new PageResponse(datas, total, pageNo, pageSize);
    }

    private void buildCompanyInfo(String schema, Map<String, Object> data) {
        if (CrmSchema.EVENT_OUTTER.equals(schema)) {
            String companyKeys = data.getOrDefault("company_keys", "" ).toString();
            companyKeys = companyKeys.replace("\"", "" );
            data.put("company_keys", companyKeys.substring(1, companyKeys.length() - 1));
            if (companyKeys.contains("," )) {
                companyKeys = companyKeys.substring(1, companyKeys.indexOf("," ));
            } else {
                companyKeys = companyKeys.substring(1, companyKeys.length() - 1);
            }
            getCompanyVo(data, companyKeys);

        } else {
            getCompanyVo(data, data.getOrDefault("customer_key", "0" ).toString());
        }
    }


    public Response searchInnerDynamics(SearchEventReqQo searchEventReqQo) {
        try {
            return searchEvents(searchEventReqQo, CrmSchema.EVENT_INNER, "customer_key", EsOperator.TERM);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.EVENT_QUERY_ERROR, e);
        }
    }

    public Response searchOuterEvents(SearchEventReqQo searchEventReqQo) {
        try {
            return searchEvents(searchEventReqQo, CrmSchema.EVENT_OUTTER, "company_keys", EsOperator.TERM);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.EVENT_QUERY_ERROR, e);
        }
    }

    public Response searchEvents(SearchEventReqQo searchEventReqQo, String schema, String filterKey, String queryType) {
        String searchType = searchEventReqQo.getSearchType();
        String source = searchEventReqQo.getSource();
        String type = searchEventReqQo.getType();
        String name = searchEventReqQo.getName();
        String startDate = searchEventReqQo.getStartDate();
        String endDate = searchEventReqQo.getEndDate();
        String dateOrder = searchEventReqQo.getDateOrder();
        String browseCountOrder = searchEventReqQo.getBrowseCountOrder();
        String favoriteCountOrder = searchEventReqQo.getFavoriteCountOrder();
        Integer pageNo = searchEventReqQo.getPageNo();
        Integer pageSize = searchEventReqQo.getPageSize();

        //用户ID列表
        List<Long> userIds = new ArrayList<>();
        //动态的公司key
        Set<String> customerKeys = new HashSet<>();
        getUserIds(userIds, searchType, CommonUtils.getUserID());
        if (userIds.size() == 0) {
            return new PageResponse(null, 0, pageNo, pageSize);
        }
        getKeys(customerKeys, userIds, source, schema);
        if (customerKeys.size() == 0) {
            return new PageResponse(null, 0, pageNo, pageSize);
        }

        /*条件查询事件*/
        SearchQoBuilder searchQoBuilder = buildSearchKeyword(schema, name, pageNo, pageSize);
        buildSearchFilter(searchQoBuilder, filterKey, customerKeys, queryType, type, startDate, endDate);
        buildSearchSort(searchQoBuilder, dateOrder, browseCountOrder, favoriteCountOrder);

        //ES RCP查询
        SearchVo searchVo = this.searchService.search(searchQoBuilder.get());
        SearchResp res = searchVo.getSearchResp();
        List<Map<String, Object>> events = JSONUtils.jsonToListMap(JSON.toJSONString(res.getData()));
        PageResponse response = buildPageResponse(schema, pageNo, pageSize, events, res.getTotal());
        return response;
    }

    private PageResponse buildPageResponse(String schema, Integer pageNo, Integer pageSize, List<Map<String, Object>> events, Long total) {
        PageResponse response = PageResponse.success();
        response.setPageInfo(total.intValue(), pageNo, pageSize);

        if (CollectionUtils.isEmpty(events))
            return response;

        if (CrmSchema.EVENT_INNER.equalsIgnoreCase(schema)) {
            List<SearchInnerDynamicResVo> innerDynamicResVos = new ArrayList<>();
            for (Map<String, Object> event : events) {
                innerDynamicResVos.add(json2InnerDynamicRes(event));
            }
            response.setPayload(innerDynamicResVos);
        } else {
            List<SearchOuterEventResVo> outerEventResVos = new ArrayList<>();
            for (Map<String, Object> event : events) {
                outerEventResVos.add(json2OuterEventRes(event));
            }
            response.setPayload(outerEventResVos);
        }
        return response;
    }

    private void getKeys(Set<String> customerKeys, List<Long> userIds, String source, String schema) {
        //1.1 管户客户
        if (CrmConstant.SOURCE_CUSTOMER_MANAGER.equalsIgnoreCase(source)) {
            List<String> entityKeys = relationItemRepo.findEntityKeys(1l, userIds);
            customerKeys.addAll(entityKeys);
        }
        //1.2 我关注的
        else if (CrmConstant.SOURCE_CONCERN_CUSTOMER.equalsIgnoreCase(source)) {
            customerKeys.addAll(concernedDao.findByUserIds(userIds.toArray(new Long[userIds.size()])));
        }
        //1.3 我收藏的
        else if (CrmConstant.SOURCE_MY_FAVOURITY.equalsIgnoreCase(source)) {
            customerKeys.addAll(favouriteDao.findEntityKeys(userIds, schema));
        }
        //1.4 分享给我的
        else if (CrmConstant.SOURCE_SHEAR_TO_ME.equalsIgnoreCase(source)) {
            customerKeys.addAll(userShareDao.findEntityKeys(userIds, schema));
        } else {
            customerKeys.addAll(relationItemRepo.findEntityKeys(1l, userIds));
            customerKeys.addAll(concernedDao.findByUserIds(userIds.toArray(new Long[userIds.size()])));
            customerKeys.addAll(favouriteDao.findEntityKeys(userIds, schema));
            customerKeys.addAll(userShareDao.findEntityKeys(userIds, schema));
        }
    }

    private void getUserIds(List<Long> userIds, String searchType, Long curUserId) {
        //1.我的行外事件
        if (CrmConstant.QUERYTYPE_MY.equalsIgnoreCase(searchType)) {
            userIds.add(curUserId);
        } else {//2.下属的行外事件
            Long deptId = departmentDao.findByManagerId(curUserId);
            if (deptId == null) {
                return;
            }
            List<Integer> userIdsTmp = userDao.findByDeptId(deptId);
            for (Integer id : userIdsTmp) {
                userIds.add(id.longValue());
            }
            //去掉我的ID
            userIds.remove(curUserId);
        }
    }

    private SearchInnerDynamicResVo json2InnerDynamicRes(Map<String, Object> event) {
        SearchInnerDynamicResVo res = new SearchInnerDynamicResVo();
        res.setName(Getter.get("title", event));
        CompanyVo companyVo = companyService.queryByCustomerKey(Getter.get("customer_key", event));
        res.setCompanyVo(companyVo);

        res.setDetailKey(Getter.get("detail_key", event));
        res.setEventDate(Getter.get("event_time", event));
        res.setLinkTo(Getter.get("link_to", event));
        res.setObjectKey(Getter.get("object_key", event));

        res.setType(Getter.get("type_", event));
        res.setBrowseCount(Long.parseLong(event.getOrDefault("browse_count", "0" ).toString()));
        res.setFavoriteCount(Long.parseLong(event.getOrDefault("favorite_count", "0" ).toString()));

        int favouriteCount = favouriteDao.findFavouriteCount(CommonUtils.getUserID(), CrmSchema.EVENT_INNER, Getter.get("object_key", event));
        res.setFavourited(favouriteCount >= 1 ? true : false);
        return res;
    }

    private SearchOuterEventResVo json2OuterEventRes(Map<String, Object> event) {
        SearchOuterEventResVo res = new SearchOuterEventResVo();
        res.setName(event.getOrDefault("title", "" ).toString());
        res.setEventDate(event.getOrDefault("event_time", "" ).toString());
        res.setObjectKey(event.getOrDefault("object_key", "" ).toString());
        res.setType(event.getOrDefault("type_", "" ).toString());
        res.setAddress(event.getOrDefault("address", "" ).toString());
        String companyKeys = event.getOrDefault("company_keys", "" ).toString();
        companyKeys = companyKeys.replace("\"", "" );
        if (companyKeys.contains("," )) {
            companyKeys = companyKeys.substring(1, companyKeys.indexOf("," ));
        } else {
            companyKeys = companyKeys.substring(1, companyKeys.length() - 1);
        }

        CompanyVo companyVo = companyService.queryByCustomerKey(companyKeys);
        res.setCompanyVo(companyVo);

        res.setDetail(event.getOrDefault("detail", "" ).toString());
        res.setIndustry(event.getOrDefault("industry", "" ).toString());
        res.setSourceWebsite(event.getOrDefault("source_website", "" ).toString());
        res.setBrowseCount(Long.parseLong(event.getOrDefault("browse_count", "0" ).toString()));
        res.setFavoriteCount(Long.parseLong(event.getOrDefault("favorite_count", "0" ).toString()));

        int favouriteCount = favouriteDao.findFavouriteCount(CommonUtils.getUserID(), CrmSchema.EVENT_OUTTER, Getter.get("object_key", event));
        res.setFavourited(favouriteCount >= 1 ? true : false);
        return res;
    }

    private SearchQoBuilder buildSearchKeyword(String schema, String keyword, Integer pageNo, Integer pageSize) {
        SearchQoBuilder searchQoBuilder = new SearchQoBuilder();
        searchQoBuilder.setGraph(CrmSchema.CRM);
        searchQoBuilder.addSchemas(schema);
        if (StringUtils.isNotBlank(keyword)) {
            searchQoBuilder.setKeyword(keyword);
            searchQoBuilder.addMatchQuery("title" );
        }
        searchQoBuilder.setPageNo(pageNo);
        searchQoBuilder.setPageSize(pageSize);
        return searchQoBuilder;
    }

    private SearchQoBuilder buildSearchFilter(SearchQoBuilder searchQoBuilder, String filterKey, Set<String> keys,
                                              String queryType, String type, String startDate, String endDate) {
        if (StringUtils.isNotBlank(type)) {
            searchQoBuilder.addTermFilter("type_", type);
        }
        if (EsOperator.TERM.equals(queryType)) {
            searchQoBuilder.addTermFilter(filterKey, keys.toArray());
        } else {
            Map<String, Object> keysMap = new HashMap<>();
            keysMap.put(EsOperator.KEY_FIELD, filterKey);
            keysMap.put(EsOperator.KEY_TYPE, EsOperator.MATCH);
            keysMap.put(EsOperator.KEY_VALUES, keys.toArray());
            searchQoBuilder.get().addFilter(keysMap);
        }
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            searchQoBuilder.addRangeFilter("event_time", startDate, endDate);
        }
        return searchQoBuilder;
    }

    private SearchQoBuilder buildSearchSort(SearchQoBuilder searchQoBuilder, String dateOrder, String browseCountOrder, String favoriteCountOrder) {
        searchQoBuilder.addSort("event_time", dateOrder);
        searchQoBuilder.addSort("browse_count", browseCountOrder);
        searchQoBuilder.addSort("favorite_count", favoriteCountOrder);
        return searchQoBuilder;
    }

    @Override
    public Response findCustomers(String queryType) {
        try {
            Long curUserId = CommonUtils.getUserID();
            List<String> customerKeys = getCustomerKeys(queryType, curUserId);
            if (CollectionUtils.isEmpty(customerKeys)) {
                return Response.success();
            }

            SearchQoBuilder searchQoBuilder = new SearchQoBuilder();
            searchQoBuilder.setGraph(CrmSchema.CRM);
            searchQoBuilder.addSchemas(CrmSchema.COMPANY);
            searchQoBuilder.addTermFilter("object_key", customerKeys.toArray());
            SearchVo searchVo = searchService.search(searchQoBuilder.get());
            SearchResp searchResp = searchVo.getSearchResp();
            if (null == searchResp || null == searchResp.getData()) {
                return Response.success();
            }

            List<Map<String, Object>> companys = JSONUtils.jsonToListMap(JSON.toJSONString(searchResp.getData()));
            List<CompanyVo> companyVos = new ArrayList<CompanyVo>();
            CompanyVo companyVo = null;
            for (Map<String, Object> map : companys) {
                companyVo = new CompanyVo();
                companyVo.setName(map.get("name" ).toString());
                companyVo.setObjectKey(map.get("object_key" ).toString());
                companyVos.add(companyVo);
            }
            return Response.success(companyVos);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.CUSTOMER_QUERY_ERROR, e);
        }
    }

    private List<String> getCustomerKeys(String queryType, Long curUserId) {
        List<String> customerKeys;
        if (CrmConstant.QUERYTYPE_UNDERLING.equals(queryType)) {
            Long deptId = departmentDao.findByManagerId(curUserId);
            List<Long> userIds = new ArrayList<Long>();
            List<Integer> userIdsTmp = userDao.findByDeptId(deptId);
            for (Integer id : userIdsTmp) {
                userIds.add(id.longValue());
            }
            userIds.remove(curUserId);
            if (userIds.size() == 0) {
                return null;
            }
            customerKeys = concernedDao.findCompanyKeysByUserIds(userIds.toArray(new Long[userIds.size()]));
        } else {
            customerKeys = concernedDao.findCompanyKeysByUserIds(new Long[]{curUserId});
        }
        return customerKeys;
    }

    @Override
    public Response findCreators() {
        try {
            Long curUserId = CommonUtils.getUserID();
            Long deptId = departmentDao.findByManagerId(curUserId);
            List<UserResultVo> userResultVos = userDao.findByUserIdAndDeptId(curUserId, deptId);
            return Response.success(userResultVos);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.VISIT_RECORD_GETCREATOR_ERROE, e);
        }
    }
}